#! /usr/bin/env python
#hmtian
import os, sys
import csv
import re

def parse_file_name( fname ):
    return fname.split('.')[0]

def run_sat( filename ):
    cmd = '/home/hkm/master_graduate_CirSAT/cstic_CirSAT/build/test_solver /home/hkm/one_PObench/'+ filename + ' > /home/hkm/master_graduate_CirSAT/cstic_CirSAT/data_csat/' + filename.split('.')[0]+'.log'
    os.system( cmd )

def extract_info_in_log( base_name ):
    path = "/home/hkm/master_graduate_CirSAT/cstic_CirSAT/data_csat/" + base_name + ".log"
    i = 0
    print(base_name)
    with open( path, 'r' ) as f:
        for line in f:
            i = i + 1
            if i == 1:  
                solution = line.split()[0]
                print(solution)
            # elif i == 2:
            #     print(line)
            #     decision_nums = line.split(":")[1]
            #     print(decision_nums)
            # elif i == 3:
            #     print(line)
            #     confict_nums = line.split(":")[1]
            #     print(confict_nums)
            # elif i == 4:
            #     print(line)
            #     parser_time = line.split()[4]
            #     print(parser_time)
            elif i == 4:
                print(line)
                solve_time = line.split()[4]
                print(solve_time)
    return base_name, solution, solve_time

if __name__ == "__main__":
    argc = len( sys.argv )
    if( argc != 1 ):
        print( "./test_date.py" )
        exit( 1 )
    else:
        #create csv file
        path = "cstic_csat.csv"
        with open(path,'w') as f:
            csv_write = csv.writer(f)
            csv_head = ["Benchmark",  "solution",  "solve_time"]
            csv_write.writerow( csv_head )

            #foreach file run abc
            file_list = os.listdir( "/home/hkm/one_PObench/" )
            sorted_file_list = sorted(file_list)
            for filename in sorted_file_list:
                run_sat( filename )
                base_name = parse_file_name( filename )
                # print(base_name)      //miter_router
                strings = extract_info_in_log( base_name )
                print(strings)
                csv_write.writerow( strings )                      
